package cn.bigcontainer.alt.meta.service.impl;

import javax.annotation.Resource;

import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.bigcontainer.alt.common.entity.BigMap;
import cn.bigcontainer.alt.common.util.WoKit;
import cn.bigcontainer.alt.common.util.WoVelocityKit;
import cn.bigcontainer.alt.meta.dao.MDao;
import cn.bigcontainer.alt.meta.dto.MObjectDto;
import cn.bigcontainer.alt.meta.mapper.MObjectMapper;
import cn.bigcontainer.alt.meta.po.MObject;
import cn.bigcontainer.alt.meta.po.MProperty;
import cn.bigcontainer.alt.meta.service.RequestJsonService;
import lombok.extern.slf4j.Slf4j;

/**
 * @author cailei
 * @date 2020年03月30日
 */
@Service
@Transactional(rollbackFor = { Exception.class })
@Primary
@Slf4j
public class RequestJsonServiceImpl implements RequestJsonService {

	@Resource
	private WoVelocityKit velocity;

	@Resource
	private MDao mDao;

	@Resource
	private MObjectMapper mObjectMapper;

	@Override
	public void executeSql(BigMap<String, Object> req) {
		String sqlString = velocity.parse(req.getString("sql"), req);
		String selectedIds = req.getString("selectedIds");
		if (WoKit.isEmpty(selectedIds) || selectedIds.indexOf(',') < 0) {
			mDao.update(sqlString);
			return;
		}
		String[] selectedIdStrings = selectedIds.split(",");
		for (String idString : selectedIdStrings) {
			req.bigPut("selectedIds", idString);
			mDao.update(velocity.parse(req.getString("sql"), req));
		}
	}

	@Override
	public void updateObject(BigMap<String, Object> req) {
		String objectId = req.getString("objectId");
		MObject mObject = mObjectMapper.selectById(objectId);
		StringBuffer sBuffer = new StringBuffer();
		for (int i = 0; i < mObject.getProperties().size(); i++) {
			MProperty property = mObject.getProperties().get(i);
			String idValue = req.getString(property.getId());
			String value = WoKit.isEmpty(idValue) ? req.getString(property.getName()) : idValue;
			if (WoKit.isEmpty(value)) {
				continue;
			}
			value = velocity.parse(value, req);
			if (sBuffer.length() > 0) {
				sBuffer.append(",");
			}
			sBuffer.append(property.getName());
			sBuffer.append("=");
			sBuffer.append("'");
			sBuffer.append(value);
			sBuffer.append("'");
		}
		String sqlString = "update " + objectId + " set " + sBuffer + " where "
				+ MObjectDto.getKeysEqualConditions(mObject, false, req.getString("selectedIds"));
		mDao.update(sqlString);
	}

}
